import time

import requests
import validators
from flask import Blueprint, jsonify, request
from sqlalchemy.orm import sessionmaker

from model.base_model import Task, engine, Testcase
from utils.log_utils import logger

task_bp = Blueprint('task', __name__, url_prefix='/api/task')


@task_bp.route('/add', methods=['POST'])
def add():
    # 解析请求消息
    try:
        req_data = request.json
        logger.info(f'请求数据===>{req_data}')
        new_task = Task(
            name=req_data.get('name'),
            total=req_data.get('total'),
            success=req_data.get('success'),
            rate=req_data.get('rate'))

        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()

        # 写入数据
        db_session.add(new_task)
        db_session.commit()
        db_session.close()
        return jsonify(code=0, msg='新增成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'新增失败，原因：{e}')


@task_bp.route('/list', methods=['GET'])
def get():
    try:
        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()

        # 查全部数据
        task_list = []
        tasks = db_session.query(Task).all()
        for t in tasks:
            task_dict = t.as_dict()
            # 格式化字符串 小数转为百分数
            task_dict['rate'] = f"{task_dict['rate']:.2%}"
            task_list.append(task_dict)

        db_session.commit()
        db_session.close()
        return jsonify(code=0, count=len(tasks), data=task_list, msg='查询成功')
    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'查询失败，原因：{e}')


@task_bp.route('/execute', methods=['POST'])
def execute():
    # 用例集的执行方式 勾选多个 点击批量运行
    # 每个用例发送请求 测试任务表中添加一条记录 几条成功几条失败 成功率是多少
    try:
        # 解析请求数据
        task_data = request.json
        case_ids = task_data.get('ids')
        # 会话
        Session = sessionmaker(bind=engine)
        db_session = Session()

        rep_data = []
        success_count = 0
        code = 0
        for case_id in case_ids:
            # 查询
            execute_case = db_session.query(Testcase).filter_by(id=case_id).first()
            if not execute_case:
                code -= 1
                rep_data.append({'id': case_id, 'result': {'code': -1, 'msg': f'执行失败，不存在id为{case_id}的测试用例'}})

            else:
                if not validators.url(execute_case.url):
                    rep_data.append({'id': case_id, 'result': {'code': -1, 'msg': f'执行失败，url不合法'}})
                    continue
                # 发送请求
                res = requests.request(method=execute_case.method, url=execute_case.url,
                                       params=execute_case.params, data=execute_case.data)

                if res.status_code == 200:
                    success_count += 1
                try:
                    rep_data.append({'id': case_id, 'result': res.json()})
                except Exception as e:
                    rep_data.append({'id': case_id, 'result': res.text})

        # 实例化任务模型对象
        # 新增任务表记录
        new_task = Task(
            name=f'测试任务_{int(time.time())}',
            success=success_count,
            total=len(case_ids),
            rate=round(success_count / len(case_ids), 2)
        )

        # 写入数据
        db_session.add(new_task)
        # 提交事务并关闭
        db_session.commit()
        db_session.close()
        return jsonify(code=0 if code == 0 else -1, data=rep_data)

    except Exception as e:
        logger.warning(f'{e}')
        return jsonify(code=-1, msg=f'查询失败，原因：{e}')
